package test.search;

import java.io.IOException;

import lucene.Searcher;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * 
 * @author Administrator
 */
public class SearchWithSort {

	/**
	 * @param args
	 * @throws ParseException
	 * @throws IOException
	 */
	public static void main(String[] args) throws ParseException, IOException {
		Searcher searcher = new Searcher();

		Query query = Searcher.createQuery("content", "happy");

		TopDocs topDocs = searcher.executeQuery(query, 1000);
		showTopDocs(topDocs, searcher);

		topDocs = searcher.executeQuery(query, 1000);
		showTopDocs(topDocs, searcher, query);

		topDocs = searcher.executeQuery(query, null, 1000, Sort.RELEVANCE);
		showTopDocs(topDocs, searcher, query);

		topDocs = searcher.executeQuery(query, null, 1000, Sort.INDEXORDER);
		showTopDocs(topDocs, searcher, query);

		topDocs = searcher.executeQuery(query, null, 1000, new Sort(
				new SortField("title", SortField.STRING,true)));
		showTopDocs(topDocs, searcher, query);

		searcher.close();
	}

	public static void showTopDocs(TopDocs topDocs, Searcher searcher,
			Query query) throws IOException {
		System.out.println("hits: " + topDocs.scoreDocs.length);
		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
			System.out.println(scoreDoc.doc);
			Document doc = searcher.doc(scoreDoc.doc);
			System.out.println(doc.getField("title").stringValue());
			// System.out.println(doc.getField("path").stringValue());
			// System.out.println(doc.getField("date").stringValue());
			Explanation explanation = searcher.explain(query, scoreDoc.doc);
			System.out.println(explanation);
		}
	}

	public static void showTopDocs(TopDocs topDocs, Searcher searcher)
			throws CorruptIndexException, IOException {
		System.out.println("hits: " + topDocs.scoreDocs.length);
		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
			System.out.println(scoreDoc.doc);
			Document doc = searcher.doc(scoreDoc.doc);
			System.out.println(doc.getField("title").stringValue());
			// System.out.println(doc.getField("path").stringValue());
			// System.out.println(doc.getField("date").stringValue());
		}

	}
}
